import { routerRedux } from 'dva/router';
import { statusOk, statusUnauthorized } from '../utils/httpcode';
import { interact } from '../config/api';

const queryUser = interact('getUser');
const signin = interact('signin');
const signout = interact('signout');

export default {
  namespace: 'user',

  state: {
    list: [],
    login: {
      status: undefined,
      submitting: false,
    },
    loading: false,
    currentUser: {},
  },

  effects: {
    *fetchCurrent(_, { call, put, select }) {
      const user = yield select(s => s.currentUser);
      if (user && user.UserId) {
        return undefined;
      }

      const response = yield call(queryUser);
      if (response.code === statusUnauthorized) {
        yield put(routerRedux.push('/user/login'));
      } else {
        if (response.code !== statusOk) {
          throw new Error(response.message);
        }

        yield put({
          type: 'saveCurrentUser',
          payload: response.message,
        });
      }
    },

    *login({ payload }, { call, put }) {
      const { code, message } = yield call(signin, payload);

      yield put({
        type: 'changeLogin',
        payload: {
          status: code !== statusOk ? message : 'ok',
        },
      });

      if (code === statusOk) {
        yield put({
          type: 'saveCurrentUser',
          payload: message,
        });
      }
    },

    *logout(_, { call, put }) {
      yield call(signout);

      yield put({
        type: 'changeLogin',
        payload: { status: false },
      });

      yield put(routerRedux.push('/user/login'));
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, { payload }) {
      return {
        ...state,
        currentUser: payload,
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload,
        },
      };
    },
    changeLogin(state, { payload }) {
      return {
        ...state,
        login: {
          ...state.login,
          ...payload,
        },
      };
    },
  },

  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'fetchCurrent' });
    },
  },
};
